<?php

namespace App\Http\Controllers\Admin;
use App\DTOS\Admin\CustomerDTO;
use App\Http\Controllers\Controller;
use App\Models\Game\PayOrderTop;
use App\Models\Game\UserMember;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Http\Request;

class RoleLoginController extends Controller
{
    private Request $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    private function buildRes(){
        $searchData = $this->request->all();
        global $gameArea;
        MyLog::info('查看ES查询条件'.json_encode($searchData));

        $res = callRpc("/RoleLoginService/paginate",$searchData,['gameArea'=>$gameArea]);
        MyLog::info('查看ES查询结果'.json_encode($res));
        if (empty($res['data'])){
            throw new \Exception("没有数据");
        }
        return $res;
    }

    public function paginate()
    {
        try {
            $res = $this->buildRes();
            return ResponseUtil::json($res);
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }

    public function export()
    {

        try {
            $searchData = $this->request->all();
            global $gameArea;
            MyLog::info('导入查询'.json_encode($searchData));

            $res = callRpc("/RoleLoginService/paginate",$searchData,['gameArea'=>$gameArea]);
            if (empty($res['data'])){
                throw new \Exception("导出查询的时候没有数据");
            }
            $excelRows = [
                ['记录时间','服务器ID','游戏账号','角色ID','角色名','角色等级','角色职业','地图ID','地图名','场景类型','平台','设备号','IP','城市','地区','运营商','事件类型']
            ];
            foreach($res['data'] as $datum){
                $excelRows[] = [
                    $datum['logTime'] ?? null,
                    $datum['serverId'] ?? null,
                    $datum['memberName'] ?? null,
                    $datum['roleId'] ?? null,
                    $datum['nick'] ?? null,
                    $datum['level'] ?? null,
                    $datum['jobName'] ?? null,
                    $datum['mapId'] ?? null,
                    $datum['mapName'] ?? null,
                    $datum['mapTypeName'] ?? null,
                    $datum['platform'] ?? null,
                    $datum['deviceCode'] ?? null,
                    $datum['ipAddress'] ?? null,
                    $datum['city'] ?? null,
                    $datum['region'] ?? null,
                    $datum['isp'] ?? null,
                    $datum['eventName'] ?? null,
                ];
            }
            return ResponseUtil::success(cacheDownload(arrayToScvContent($excelRows),'.登录日志.csv'));
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }

    public function filter()
    { //table 数据导出
        // 分页参数
        $page = $this->request->input('page', 1);
        $pageSize = $this->request->input('limit', 10);
        $dto = new CustomerDTO($this->request->all());
        $createDateBegin = $dto->getCreateDateBegin();
        $createDateEnd = $dto->getCreateDateEnd();
        $gameArea = $dto->getGameArea();
        global $gameArea;


        $input_str = "1,2,3,4";
        $input_numbers = explode(',', $input_str);
        $results = array();
        $searchData['createDateBegin']=$createDateBegin;
        $searchData['createDateEnd']=$createDateEnd;
        $res = callRpc("/RoleLoginService/filter",$searchData,['gameArea'=>$gameArea]);
        if (empty($res['data'])){
            throw new \Exception("没有数据");
        }
        //筛选出相同ip地址的数据

        $res1 = $this->filterIp($res['data']);
        $memIds = collect($res1)->pluck('memId')->unique()->toArray();
        $roleids = collect($res1)->pluck('roleId')->unique()->toArray();

        $members = UserMember::query()->whereIn('id', $memIds)->pluck('openid', 'id');
        $payOrderTops = PayOrderTop::query()->whereIn('role_id', $roleids)->pluck('sumfee', 'role_id');
        MyLog::info('有多少人充值这帮人'.json_encode($payOrderTops));
        foreach ($res1 as &$item) {
            $memId = $item['memId'];
            $roleid= $item['roleId'];
            if (isset($members[$memId])) {
                $item['openid'] = strval($members[$memId]);
            }

            // 获取 sumfee
            if (isset($payOrderTops[$roleid])) {
                $item['fee'] = strval($payOrderTops[$roleid]); // 使用 payOrderTops 数组获取 sumfee
            }

        }
        // 数据总数
        $totalCount = count($res1);
        // 计算分页起始索引
        $startIndex = ($page - 1) * $pageSize;
        // 获取分页数据
        $pagedData = array_slice($res1, $startIndex, $pageSize);
        // 构建返回结果
        $response = [];
        $response['code'] = 0;
        $response['count'] = $totalCount;
        $response['data'] = $pagedData;
        return ResponseUtil::json($response);
    }
    public function filterIp($data)
    {
        $duplicateIPServices = [];
        foreach ($data as &$item) {
            $deviceId = $item['deviceId'];
            if ($deviceId) {
                // 提取 IP 和 Mac
                preg_match('/IP:([^|]+)\|Mac:([^|]+)/', $deviceId, $matches);
                $ip = isset($matches[1]) ? $matches[1] : null;
                $mac = isset($matches[2]) ? $matches[2] : null;
                // 存储 IP
                $item["ip"] = $ip;
            }
        }
        $filteredData = array(); // 用于保存筛选后的数据

        // 遍历数据数组
        foreach ($data as $item) {
            if (isset($item['ip']) && $item['ip'] !== null) {
                $ip = $item['ip'];

                if (!isset($filteredData[$ip])) {
                    $filteredData[$ip] = array();
                }

                $filteredData[$ip][] = $item;
            }
        }

        // 筛选出具有相同 IP 值的数据
        $filteredArray = array();
        foreach ($filteredData as $ip => $items) {
            if (count($items) > 2) {
                $filteredArray = array_merge($filteredArray, $items);
            }
        }
        $uniqueRoleIds = array(); // 用于保存去重后的 roleId 值
        $filteredDataend = array(); // 用于保存去重后的数据

        foreach ($filteredArray as $item) {
            $roleId = $item['roleId'];

            if (!in_array($roleId, $uniqueRoleIds)) {
                $uniqueRoleIds[] = $roleId;
                $filteredDataend[] = $item;
            }
        }
        return $filteredDataend;
    }




    public function filterExport()
    {
        try {
            $dto = new CustomerDTO($this->request->all());
            $createDateBegin = $dto->getCreateDateBegin();
            $createDateEnd = $dto->getCreateDateEnd();


            $gameArea = $dto->getGameArea();
            global $gameArea;

            $searchData['createDateBegin']=$createDateBegin;
            $searchData['createDateEnd']=$createDateEnd;
            $res = callRpc("/RoleLoginService/filter",$searchData,['gameArea'=>$gameArea]);
            if (empty($res['data'])){
                throw new \Exception("没有数据");
            }

            $res1 = $this->filterIp($res['data']);
            $memIds = collect($res1)->pluck('memId')->unique()->toArray();
            $roleids = collect($res1)->pluck('roleId')->unique()->toArray();

            $members = UserMember::query()->whereIn('id', $memIds)->pluck('openid', 'id');
            $payOrderTops = PayOrderTop::query()->whereIn('role_id', $roleids)->pluck('sumfee', 'role_id');

            foreach ($res1 as &$item) {
                $memId = $item['memId'];
                $roleid= $item['roleId'];

                if (isset($members[$memId])) {
                    $item['openid'] = (string)$members[$memId];
                }
                // 获取 sumfee
                if (isset($payOrderTops[$roleid])) {
                    $item['fee'] = strval($payOrderTops[$roleid]); // 使用 payOrderTops 数组获取 sumfee
                }
            }

            $excelRows = [
                ['记录时间','服务器ID','长ID','角色ID','角色名','累充金额','角色等级','角色职业','地图ID','地图名','场景类型','平台','设备号','IP','城市','地区','运营商','事件类型']
            ];
            foreach($res1 as $datum){

                $excelRows[] = [
                    $datum['logTime'] ?? null,
                    $datum['gameArea'] ?? null,
                    "ID:".$datum['openid'] ?? null,
                    $datum['roleId'] ?? null,
                    $datum['nick'] ?? null,
                    $datum['fee'] ?? null,
                    $datum['level'] ?? null,
                    $datum['jobName'] ?? null,
                    $datum['mapId'] ?? null,
                    $datum['mapName'] ?? null,
                    $datum['mapTypeName'] ?? null,
                    $datum['platform'] ?? null,
                    $datum['deviceId'] ?? null,
                    $datum['ip'] ?? null,
                    $datum['city'] ?? null,
                    $datum['region'] ?? null,
                    $datum['isp'] ?? null,
                    $datum['eventName'] ?? null,
                ];
            }
            return ResponseUtil::success(cacheDownload(arrayToScvContent($excelRows),'.问题账号.csv'));
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }


    private function AlarmbuildRes(){
        $searchData = $this->request->all();
        global $gameArea;
        $res = callRpc("/RoleAlarmLogsService/paginate",$searchData,['gameArea'=>$gameArea]);
        if (empty($res['data'])){
            throw new \Exception("没有数据");
        }
        return $res;
    }

    public function paginateAlarm()
    {
        try {
            $res = $this->AlarmbuildRes();
            return ResponseUtil::json($res);
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }


}
